package co.edu.uniandes.sd.mundo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;


public class SntpUtil
{
	public static Date getTimeStamp(double destinationTimestamp)
	{
		return NtpMessage.getTimeStamp(destinationTimestamp);
	}
	
	public static Date darHoraOficial() throws Exception
	{
		String serverName;
		
		serverName = "horalegal.sic.gov.co";
		
		// Send request
		DatagramSocket socket = new DatagramSocket();
		InetAddress address = InetAddress.getByName(serverName);
		byte[] buf = new NtpMessage().toByteArray();
		DatagramPacket packet =
			new DatagramPacket(buf, buf.length, address, 123);
		
		// Set the transmit timestamp *just* before sending the packet
		// ToDo: Does this actually improve performance or not?
		NtpMessage.encodeTimestamp(packet.getData(), 40,
			(System.currentTimeMillis()/1000.0) + 2208988800.0);
		
		socket.send(packet);
		
		
		// Get response
		System.out.println("NTP request sent, waiting for response...\n");
		packet = new DatagramPacket(buf, buf.length);
		socket.receive(packet);
		
		// Immediately record the incoming timestamp
		double destinationTimestamp =
			(System.currentTimeMillis()/1000.0) + 2208988800.0;
		
		
		// Process response
		NtpMessage msg = new NtpMessage(packet.getData());
		
		// Corrected, according to RFC2030 errata
		double roundTripDelay = (destinationTimestamp-msg.originateTimestamp) -
			(msg.transmitTimestamp-msg.receiveTimestamp);
			
		double localClockOffset =
			((msg.receiveTimestamp - msg.originateTimestamp) +
			(msg.transmitTimestamp - destinationTimestamp)) / 2;
		

		Double d1 = new Double(localClockOffset);
		Double d2 = new Double(roundTripDelay);
		long time = getTimeStamp(destinationTimestamp).getTime()+d1.longValue()*1000+d2.longValue()*1000;
		
		Date tmp = new Date(time);
		System.out.println(tmp);
		
		socket.close();
		
		return tmp;
	}
	
}
